const { Tab } = require('../../assets/libs/zanui/index');
var util = require('../../utils/util.js');

var app = getApp();
Page(Object.assign({}, Tab, {
  data: {
    userLocation:wx.getStorageSync('userLocation'),
    timeType:true,
    total:"~",
  	cdnUrl: '',
  	isHidden: true,
  	orderResult: false,
		orderResultMsg: '',//默认下单尘工提示语
  	radioItems: [
  		{name: '企业', value: '0', checked: false},
  		{name: '家庭', value: '1', checked: false}
  	],
  	region: ['请选择', '', ''],
  	valueRegion: [0, 0, 0],
  	id:0,//地址id
  	userAddress: { is_default:false},//地址详情
  	cityId:0,
  	district:[],
  	multiArray:[],
  	multiIndex: [0, 0, 0],
		remarks:"",
    loading: false,
    nodata: false,
    nomore: false,
  	/* 自定义导航栏参数 */
  	loading: false,
  	color: '#FFFFFF',
  	background: '#02B3BA',
  	show: true,
  	animated: false,
  	back: true,
    title: '预约回收',
    removeId:"",
    hsItems:[
    ],

    /*定义订单表单元素*/
    form:{
      /* 以下注释为默认为空 */
      estimate_weight:"1-25公斤",
      typedata: '',
      ordertime: '',
      name: '',
      mobile: '',
			user_address_id: 0,
      address: '',//省市区的标志
      address_detail: '',
      images: [],
      remarks:"",
      goodsinfo:[
      ]
    },
		optionTime: true,//控制时间选择弹窗  “立即预约”或者选择时间
		dateStart: '',
		timeStart: '',
		
		cregion: ['', ''],
		cvalueRegion: [0, 0],
		cdistrict:[],
		cmultiArray:[],
		cmultiIndex: [0, 0],
		addressList:[],
		addressHide: 1,
		maskShow: 0,
    sureAddressId: null,
    flActive:0,
    topArray:[
      "废纸",
      "塑料",
      "金属",
      "电器",
      "旧衣物",
      "其他",
    ],
    addressList:[],
    weightAcitve:1,
    minWeight:1,
    maxWeight:25
  },
  /* 获取最后一次下单的基本信息*/
  lastOrderInfo: function(){
    var that = this;
    app.request('/addons/cms/wxapp.user/lastOrderInfo', {}, function (data, ret) {
      that.setData({
        ['form.typedata']: data.hasOwnProperty('typedata')?data.typedata:'',
        ['form.name']: data.hasOwnProperty('name')?data.name:'',
        ['form.mobile']: data.hasOwnProperty('mobile')?data.mobile:'',
        ['form.user_address_id']: data.hasOwnProperty('user_address_id')?data.user_address_id:0,
        ['form.address']: data.hasOwnProperty('address')?data.address:'',
        ['form.address_detail']: data.hasOwnProperty('address_detail')?data.address_detail:'',
        sureAddressId: data.hasOwnProperty('user_address_id')?data.user_address_id:0
      });
      if(data.hasOwnProperty('typedata')){
        that.setData({
          ['radioItems['+data.typedata+'].checked']: true
        });
      }
    }, function (data, ret) {
      
    });
  },
	uploadImages: function (e) {
	  if (!app.globalData.userInfo) {
			app.showLoginModal(e);
	    // app.error("请登录后再操作");
	    return false;
	  }
	  var that = this;
	  wx.chooseImage({
	    success: function (res) {
	      var tempFilePaths = res.tempFilePaths;
	      var formData = app.globalData.config.upload.multipart;
	      formData.token = app.globalData.userInfo.token;
				tempFilePaths.forEach(function(item, index){
					wx.uploadFile({
					  url: app.globalData.config.upload.uploadurl,
					  filePath: item,
					  name: 'file',
					  formData: formData,
					  success: function (res) {          
					    if(res.statusCode != 200){
					      app.error(res.errMsg);
					      return;
					    }
					    var row = JSON.parse(res.data);
							var imgs = that.data.form.images;
							imgs.push(row.data);
							that.setData({
								["form.images"]: imgs
							})
							
					  }, error: function (res) {
					    app.error("上传头像失败!");
					  }
					});
				})
	      
	    }, error: function (res) {
	      app.error("上传头像失败!");
	    }
	  });
	},
	delImage: function(e){
		var that=this;
		var offset = e.currentTarget.dataset.index;
		var images = that.data.form.images;
		var imgs = [];
		images.forEach(function(item, index){
			if(offset!=index){
				imgs.push(item);
			}
		})
		that.setData({
			['form.images']: imgs
		})
	},
	addressDetailChange: function(e){
		console.log(e);
		var value = e.detail.value;
		this.setData({
			['form.address_detail']: value
		})
	},
	nameChange: function(e){
		console.log(e);
		var value = e.detail.value;
		this.setData({
			['form.name']: value
		})
	},
	mobileChange: function(e){
		console.log(e);
		var value = e.detail.value;
		this.setData({
			['form.mobile']: value
		})
	},
	radioChange: function(e){
		var value = e.detail.value;
		this.setData({
			['form.typedata']: value
		})
	},
	dateChange: function (e){
		var value = e.detail.value;
		this.setData({
			['form.ordertime']: value
		})
	},
	timeChange: function (e){
    console.log(e);
    var type=e.currentTarget.dataset.value;
    if(type=="1"){
      this.immediateTime();
      this.setData({
        timeType: true
      })
    }else{
      var value = this.data.dateStart+' '+e.detail.value;
      this.setData({
        ['form.ordertime']: value,
        optionTime: true,
        timeType: false
      })
    }
	},
	/* 立即预约 */
	immediateTime: function (){
			// a) 时间选择处，有个【即时】，表示当前时间的10分钟后
		var timestamp = Date.parse(new Date())+10*60*1000;
		var date = new Date(timestamp);
		//获取年份  
		var Y =date.getFullYear();
		//获取月份  
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		//获取当日日期 
		var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
		const hour = date.getHours();
		const minute = date.getMinutes()
		this.setData({
		  dateStart: Y + '-'  + M+ '-' + D,
			timeStart: hour + ':'  + minute
		});
		var value = Y + '-'  + M+ '-' + D +' '+ hour + ':'  + minute;
		this.setData({
			['form.ordertime']: value,
			optionTime: true
    })
    console.log(this.data.form.ordertime);
	},
	
	optionTimeHidden: function() {
	    this.setData({
	        optionTime: true//隐藏模态框
	    })
	},
	optionTimeShow: function() {
	    this.setData({
	        optionTime: false//隐藏模态框
	    })
	},
  onLoad: function (e) {
		if (!app.globalData.userInfo) {
			app.showLoginModal(e);
		  // app.error("请登录后再操作");
		  return false;
		}
    var that = this;
    console.log(e.type);
    that.setData({
      cdnUrl: app.cdnUrl,
      category_id:parseInt(e.type)
    });
		app.request('/api/index/category', {}, function (data, ret) {//获取物品信息
      console.log("category",data);
      var flActive="";
      for (let index = 0; index < data.length; index++) {
        const element = data[index];
        console.log(e.type,element.id);
        if(e.type==element.id){
          flActive=index
        }
      }
      console.log("flActive",flActive);
      that.setData({
        topArray:data,
        flActive:parseInt(flActive),
      });
      that.categorytwo(e.type)
		}, function (data, ret) {
		  app.error(ret.msg);
		});
    that.getDate();
    that.recovery_weight()
  },
  categorytwo(id){
    var that = this;
    app.request('/api/index/categorytwo', {id:id}, function (data, ret) {//获取物品信息
      console.log("categorytwo",data);
      that.setData({
        optionalArray:data
      });
    }, function (data, ret) {
      app.error(ret.msg);
    });
},
  recovery_weight(){
    var that = this;
      app.request('/api/index/recovery_weight', {}, function (data, ret) {//获取物品信息
        console.log("recovery_weight",data);
        that.setData({
          cdistrict: data
        });
      }, function (data, ret) {
        app.error(ret.msg);
      });
  },
	addressList: function () {
	  var that = this;
	  app.request('/addons/cms/wxapp.user/addressList', {}, function (data, ret) {
	    that.setData({
	      addressList: data,
	    });
	  }, function (data, ret) {
	    app.error(ret.msg);
	  });
  },
  choiceAddress: function(){
		this.addressList();
		this.setData({
			addressHide: 0,
			maskShow: 1
		})
  },
  onClickHide(){
    this.setData({
			addressHide: 1,
		})
  },
	onShow: function(){
		this.addressList();
    var that = this;
	},
	/* 获取当前日期 */
	getDate: function(){
		var timestamp = Date.parse(new Date());
		var date = new Date(timestamp);
		//获取年份  
		var Y =date.getFullYear();
		//获取月份  
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		//获取当日日期 
		var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var dateAfterHour = new Date(timestamp+60*60*1000);
		const hour = dateAfterHour.getHours();
		const minute = date.getMinutes()
		this.setData({
		  dateStart: Y + '-'  + M+ '-' + D,
			timeStart: hour + ':'  + minute
		});
	},
  onShareAppMessage: function () {
    return {
      title: '',
      desc: '',
      path: '/page/index/index'
    }
  },
  
  initialize:function(){
    let that = this, province = [], city = [], area = [];
    if (that.data.district.length) {
      let cityChildren = that.data.district[0].c || [];
      let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
      that.data.district.forEach(function (item) {
        province.push(item.n);
      });
      cityChildren.forEach(function (item) {
        city.push(item.n);
      });
      areaChildren.forEach(function (item) {
        area.push(item.n);
      });
      that.setData({
        multiArray: [province, city, area],
      });
    }
  },
  bindRegionChange: function (e) {
    let multiIndex = this.data.multiIndex, province = this.data.district[multiIndex[0]] || { c: [] }, city = province.c[multiIndex[1]] || { v: 0 }, multiArray = this.data.multiArray, value = e.detail.value;
    this.setData({
			["form.address"]: multiArray[0][value[0]]+multiArray[1][value[1]]+multiArray[2][value[2]],
      region: [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]],
      cityId: city.v,
      valueRegion: [0,0,0]
    });
    this.initialize();
  },
  bindMultiPickerColumnChange:function(e){
    let that = this, column = e.detail.column, value = e.detail.value, currentCity = this.data.district[value] || { c: [] }, multiArray = that.data.multiArray, multiIndex = that.data.multiIndex;
    multiIndex[column] = value;
    switch (column){
      case 0:
        let areaList = currentCity.c[0] || { c: [] };
        multiArray[1] = currentCity.c.map((item)=>{
          return item.n;
        });
        multiArray[2] = areaList.c.map((item)=>{
          return item.n;
        });
      break;
      case 1:
        let cityList = that.data.district[multiIndex[0]].c[multiIndex[1]].c || [];
        multiArray[2] = cityList.map((item)=>{
          return item.n;
        });
      break;
      case 2:
      
      break;
    }
    this.setData({ multiArray: multiArray, multiIndex: multiIndex});
  },
  /* 弹窗 */
  showMd: function(e) {
      var that = this;
      // var id = e.currentTarget.dataset.id - 1;
      this.setData({
          isHidden: false,//显示模态框，
          // indexModel: that.data.modelList[id],
      })
  },
  hiddenMd: function() {
      this.setData({
          isHidden: true//隐藏模态框
      })
  },
  /* 下单成功提示 */
  show_msg: function(e) {
      var that = this;
      // var id = e.currentTarget.dataset.id - 1;
      this.setData({
          isHiddenOrder: false,//显示模态框，
          // indexModel: that.data.modelList[id],
      })
  },
  hidden_msg: function() {
      this.setData({
        orderResult: false//隐藏模态框
      })
      wx.redirectTo({
        url: '/page/order/index'
      })
   
  },
	/* 回收物品分类选择 */
	categoryInitialize:function(){
	  let that = this, top = [], second = [];
	  if (that.data.cdistrict.length) {
	    let topChildren = that.data.cdistrict[0].c || [];
	    that.data.cdistrict.forEach(function (item) {
	      top.push(item.n);
	    });
	    topChildren.forEach(function (item) {
	      second.push(item.n);
      });
      console.log("top",top);
      console.log("second",second);

	    that.setData({
        active:0,
	      cmultiArray: [top, second],
	    });
	  }
	},
	bindCategoryChange: function (e) {
		var that=this;
	  let cmultiIndex = that.data.cmultiIndex, top = that.data.cdistrict[cmultiIndex[0]] || { c: [] }, second = top.c[cmultiIndex[1]] || { v: 0 }, cmultiArray = that.data.cmultiArray, value = e.detail.value;
		var offset = e.currentTarget.dataset.index;
		var goodsinfo = that.data.form.goodsinfo;
		var goods = [];
		goodsinfo.forEach(function(item, index){
			if(offset==index){
				var info = {
					recovery_category_name: cmultiArray[1][value[1]]==""?cmultiArray[0][value[0]]:cmultiArray[0][value[0]]+","+cmultiArray[1][value[1]],
					recovery_category_id: second.v,
					weight: item.weight,
          unit: second.u,
				};
				goods.push(info);
			}else{
				goods.push(item);
			}
		})
		that.setData({
			['form.goodsinfo']: goods,
			cvalueRegion: [0,0]
		})
	  this.categoryInitialize();
	},
	bindCategoryColumnChange:function(e){
	  let that = this, column = e.detail.column, value = e.detail.value, currentCity = this.data.cdistrict[value] || { c: [] }, cmultiArray = that.data.cmultiArray, cmultiIndex = that.data.cmultiIndex;
	  cmultiIndex[column] = value;
	  switch (column){
	    case 0:
	      let areaList = currentCity.c[0] || { c: [] };
	      cmultiArray[1] = currentCity.c.map((item)=>{
	        return item.n;
	      });
	    break;
	    case 1:
	    break;
	    case 2:
	    
	    break;
	  }
	  this.setData({ cmultiArray: cmultiArray, cmultiIndex: cmultiIndex});
	},
	weightChange: function(e){
    console.log(e);
    var that=this;
    var weightAcitve=e.currentTarget.dataset.id
    var offset=e.currentTarget.dataset.index
    var minWeight=0
    var maxWeight=0
    var estimate_weight=""
    var weight = ""
    if(weightAcitve==1){
       minWeight=1
       maxWeight=25
       estimate_weight="1-25公斤"
       weight="1-25"
    }
    if(weightAcitve==2){
      minWeight=25
      maxWeight=50
      estimate_weight="25-50公斤"
      weight="25-50"
    }
    if(weightAcitve==3){
      minWeight=50
      maxWeight=250
      estimate_weight="50-250公斤"
      weight="50-250"
    }
    if(weightAcitve==4){
      minWeight=250
      maxWeight=0
      estimate_weight=">250公斤"
      weight="250"
    }
    var hsList = that.data.hsItems;
    var hsListNew = [];
    console.log(hsList);
    hsList.forEach(function(item, index){
      if(offset==index){
        item.weightAcitve=weightAcitve
        hsListNew.push(item)
      }else{
        hsListNew.push(item)
      }
    })

    var goodsinfo = that.data.form.goodsinfo;
		var goods = [];
		goodsinfo.forEach(function(item, index){
			if(offset==index){
				var info = {
					recovery_category_name: item.recovery_category_name,
					recovery_category_id: item.recovery_category_id,
					weight: weight,
          unit: item.unit
				};
				goods.push(info);
			}else{
				goods.push(item);
			}
		})
		that.setData({
      ['form.goodsinfo']: goods,
      ['form.estimate_weight']: estimate_weight,
       weightAcitve:weightAcitve,
       minWeight:minWeight,
       maxWeight:maxWeight,
       hsItems:hsListNew
    })
    console.log(that.data.form.goodsinfo)
    this.calculation()
	},
	addGoods: function(e){
		var that=this;
		var offset = e.currentTarget.dataset.index;
		var goodsinfo = that.data.form.goodsinfo;
		var goods = {
			recovery_category_name: '请选择',
			recovery_category_id: 0,
			weight: '',
      unit: ''
		};
		goodsinfo.push(goods);
		that.setData({
			['form.goodsinfo']: goodsinfo
		})
	},
	delGoods: function(e){
		var that=this;
		var offset = e.currentTarget.dataset.index;
		var goodsinfo = that.data.form.goodsinfo;
		var goods = [];
		goodsinfo.forEach(function(item, index){
			if(offset!=index){
				goods.push(item);
			}
		})
		that.setData({
			['form.goodsinfo']: goods
		})
	},
	
	/* 提交预约信息 */
	order: function (e){
		if (!app.globalData.userInfo) {
			app.showLoginModal(e);
		  return false;
		}
		var that = this;
		var form = that.data.form;
		// if(form.typedata=='') {
		// 	app.error('请选择客户类型');
		// 	return false;
		// }
		if(form.ordertime==''&&this.data.timeType) {
        this.immediateTime()
		}
		if(form.name=='') {
			app.error('请选择回收地址');
			return false;
		}
		if(form.mobile=='') {
			app.error('请选择回收地址');
			return false;
		}
		if(form.address=='') {
			app.error('请选择回收地址');
			return false;
		}
		// if(form.images.length==0) {
		// 	app.error('请上传物品照片');
		// 	return false;
		// }
		if(this.data.hsItems.length==0) {
			app.error('请选择添加物品');
			return false;
		}else{
      var category_two_value=""
			this.data.hsItems.forEach(function(item, index){
        category_two_value+=item.id+","
      })
      this.setData({
        category_two_value:category_two_value
      })
    }
    console.log("that.data.ordertime",that.data.ordertime);
    that.setData({
      ['form.category_id']:that.data.category_id,
      ['form.category_two_value']:that.data.category_two_value
    });
    var formData = JSON.stringify(that.data.form);
    console.log("formData",formData);
    wx.showLoading({
      title: '提交中...',
    })
		app.request('/addons/cms/wxapp.recovery/order', {data: formData}, function(data, ret) {
      wx.hideLoading()
      console.log(data);
      if( that.data.form.typedata==0){
        that.setData({
        	// orderResultMsg: "企业用户需联系客服电话 "+app.globalData.config.customer_service_mobile+" 我们有专人专车为您服务",
          orderResultMsg: "客服联系电话"+app.globalData.config.customer_service_mobile,
        	orderResult: true// 提示框开关
        })
      }else{
        that.setData({
        	orderResultMsg: "客服联系电话"+app.globalData.config.customer_service_mobile,
        	orderResult: true// 提示框开关
        })
      }
			
      /* 企业类型提示*/
      // if(formData.typedata=='0'){
      //   that.setData({
      //   	orderResult: true// 提示框开关
      //   })
      // }
//			setTimeout(function(){
//				wx.navigateTo({
//					url: '/page/order/index'
//				})
//			},3000)
		}, function(data, ret) {
		  app.error(ret.msg);
			return false;
		});
	},
  /* 拨打客服电话*/
  callphone: function(){
    wx.makePhoneCall({
      phoneNumber: app.globalData.config.customer_service_mobile
    })
  },
	maskbind: function (event) {
		var that = this;
		that.setData({
			addressHide: 1,
			maskShow: 0,
		})
	},
	choiceAddress: function(){
		this.addressList();
		this.setData({
			addressHide: 0,
			maskShow: 1
		})
	},
	//选择默认地址
	areaChange: function (e) {
    console.log(e);
		var that = this;
		let id = e.detail.value;
    that.setData({
      sureAddressId: id
    });
	},
  sureAddress: function(){
    var that = this;
    let id = that.data.sureAddressId;
    console.log(id);
    if (id !=null) {
      var data=this.data.addressList[id]
      that.setData({
        ['form.name']: data.name,
        ['form.mobile']: data.mobile,
        ['form.user_address_id']: data.id,
        ['form.address']: data.address,
        ['form.address_detail']: data.address_detail,
        addressHide: 1,
        maskShow: 0
      });
      console.log(that.data.form);
    }
  },
  removeItem(e) {
    console.log(e);
    var anmiaton = e.currentTarget.dataset.class;
    var id = e.currentTarget.dataset.id;
    var that = this;
    var optionaList=this.data.optionalArray;
    var hsList=this.data.hsItems;
    var hsListNew=[]
    console.log(hsList);
    var goodsinfo=[];
    for (let index = 0; index < hsList.length; index++) {
      const element = hsList[index];
          if(element.id!=id){
            hsListNew.push(element)
          }else{
            optionaList.push(element)
          }
    }
    // that.setData({
    //   animation: anmiaton,
    //   removeId: e.currentTarget.dataset.id
    // })
    var goodsinfo = that.data.form.goodsinfo;
		var goods = [];
		goodsinfo.forEach(function(item, index){
			if(item.recovery_category_id!=id){
				goods.push(item);
			}
		})
		that.setData({
      ['form.goodsinfo']: goods,
      hsItems:hsListNew,
      optionalArray:optionaList
    })
    console.log(that.data.form);
    // setTimeout(function() {
    //   that.setData({
    //     animation: '',
    //     removeId: "", 
    //     hsItems:hsListNew,
    //     optionalArray:optionaList
    //   })
    //   that.calculation();//计算合计
    // }, 0)
  },
  addItem(e) {
    console.log(e);
    var anmiaton = e.currentTarget.dataset.class;
    var id = e.currentTarget.dataset.id;
    var that = this;
    var optionaList=this.data.optionalArray;
    var optionaListNew=[]
    var hsListNew=this.data.hsItems
    var goodsinfo=this.data.form.goodsinfo;
    for (let index = 0; index < optionaList.length; index++) {
      const element = optionaList[index];
          if(element.id!=id){
            optionaListNew.push(element)
          }else{
            element.weightAcitve='1'
            hsListNew.push(element)
            goodsinfo.push({
                recovery_category_name: element.name,
                recovery_category_id: element.id,
                weight: '1-25',
                unit: 'KG'//默认单位为kg
            })
          }
    }
    that.setData({
      // animation: anmiaton,
      // removeId: e.currentTarget.dataset.id,
      ['form.goodsinfo']: goodsinfo,
    })
    console.log(that.data.form);
    setTimeout(function() {
      that.setData({
        // animation: '',
        // removeId: "", 
        hsItems:hsListNew,
        optionalArray:optionaListNew
      })
      that.calculation();//计算合计
    }, 0)
  },
  onChange(e){
    var index=e.detail.index
    var item=this.data.topArray[index]
    this.setData({
      hsItems:[],
    	['form.goodsinfo']: [],
      optionalArray:[],
      category_id:item.id
    })
    this.categorytwo(item.id);
  },
  calculation(){
    var hsList =this.data.hsItems
    var weight=this.data.weightAcitve
    var minTotal=0;
    var maxTotal=0;
    for (let index = 0; index < hsList.length; index++) {
      const element = hsList[index];
      console.log(element);
      minTotal=minTotal+(parseFloat(element.price) * this.data.minWeight)
      maxTotal=maxTotal+(parseFloat(element.price) * this.data.maxWeight)
      console.log(minTotal,maxTotal);
    }
    if(this.data.maxWeight==0){maxTotal=9999}
    if(hsList.length==0){
      this.setData({
        total:"~"
      })
    }else{
      this.setData({
        total:minTotal.toFixed(2)+"~"+maxTotal.toFixed(2)
      })
    }
   
  }
}))
